import { DataTypes, Model, Optional } from 'sequelize';
import sequelize from '../db';

/**
 * 动态表格配置模型
 */

// 字段类型枚举
export enum FieldType {
  TEXT = 'text',
  NUMBER = 'number',
  SELECT = 'select',
  DATE = 'date',
  DATETIME = 'datetime',
  SWITCH = 'switch',
  RADIO = 'radio',
  CHECKBOX = 'checkbox',
  TEXTAREA = 'textarea',
  IMAGE = 'image',
  FILE = 'file',
}

// 字段配置接口
interface FieldConfig {
  key: string;
  label: string;
  type: FieldType;
  table?: {
    width?: number | string;
    align?: 'left' | 'center' | 'right';
    fixed?: 'left' | 'right' | false;
    sortable?: boolean;
    hidden?: boolean;
  };
  search?: {
    searchable: boolean;
    searchType?: 'equal' | 'like' | 'range' | 'in';
    quickSearch?: boolean;
  };
  form?: {
    editable: boolean;
    creatable: boolean;
    updatable: boolean;
    rules?: Array<{
      required?: boolean;
      min?: number;
      max?: number;
      message?: string;
    }>;
    placeholder?: string;
    options?: Array<{
      label: string;
      value: any;
    }>;
  };
}

// 表格配置接口
export interface TableConfigAttributes {
  id: string;
  tenantId?: string;
  code: string; // 表格唯一标识
  name: string; // 表格名称
  description?: string;
  tableName: string; // 对应的数据库表名
  apiPath?: string; // API路径前缀
  fields: FieldConfig[]; // 字段配置
  actions?: {
    create?: boolean;
    update?: boolean;
    delete?: boolean;
    batchDelete?: boolean;
    export?: boolean;
    import?: boolean;
  };
  tableProps?: {
    bordered?: boolean;
    size?: 'large' | 'middle' | 'small';
    pagination?: boolean | {
      pageSize?: number;
    };
  };
  permissions?: {
    view?: string;
    create?: string;
    update?: string;
    delete?: string;
  };
  status: boolean;
  createdBy?: string;
  updatedBy?: string;
  createdAt?: Date;
  updatedAt?: Date;
}

export interface TableConfigCreationAttributes
  extends Optional<
    TableConfigAttributes,
    'id' | 'tenantId' | 'description' | 'apiPath' | 'actions' | 'tableProps' | 'permissions' | 'createdBy' | 'updatedBy' | 'createdAt' | 'updatedAt'
  > {}

class TableConfig extends Model<TableConfigAttributes, TableConfigCreationAttributes> {
  public id!: string;
  public tenantId?: string;
  public code!: string;
  public name!: string;
  public description?: string;
  public tableName!: string;
  public apiPath?: string;
  public fields!: FieldConfig[];
  public actions?: any;
  public tableProps?: any;
  public permissions?: any;
  public status!: boolean;
  public createdBy?: string;
  public updatedBy?: string;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  /**
   * 获取表格配置
   */
  static async getConfigByCode(code: string, tenantId?: string): Promise<TableConfig | null> {
    const where: any = { code, status: true };
    if (tenantId) {
      where.tenantId = tenantId;
    }
    
    return await this.findOne({ where });
  }

  /**
   * 获取租户的所有表格配置
   */
  static async getTenantConfigs(tenantId?: string): Promise<TableConfig[]> {
    const where: any = { status: true };
    if (tenantId) {
      where.tenantId = tenantId;
    }

    return await this.findAll({ 
      where,
      order: [['name', 'ASC']]
    });
  }
}

TableConfig.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'tenant_id',
    },
    code: {
      type: DataTypes.STRING(50),
      allowNull: false,
      unique: true,
      comment: '表格配置唯一标识',
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '表格名称',
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '表格描述',
    },
    tableName: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'table_name',
      comment: '对应的数据库表名',
    },
    apiPath: {
      type: DataTypes.STRING(200),
      allowNull: true,
      field: 'api_path',
      comment: 'API路径前缀',
    },
    fields: {
      type: DataTypes.JSON,
      allowNull: false,
      comment: '字段配置JSON',
    },
    actions: {
      type: DataTypes.JSON,
      allowNull: true,
      defaultValue: {
        create: true,
        update: true,
        delete: true,
        batchDelete: false,
        export: false,
        import: false,
      },
      comment: '操作权限配置',
    },
    tableProps: {
      type: DataTypes.JSON,
      allowNull: true,
      field: 'table_props',
      defaultValue: {
        bordered: false,
        size: 'middle',
        pagination: { pageSize: 10 },
      },
      comment: '表格属性配置',
    },
    permissions: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '权限配置',
    },
    status: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: true,
      comment: '状态',
    },
    createdBy: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'created_by',
    },
    updatedBy: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'updated_by',
    },
  },
  {
    sequelize,
    modelName: 'TableConfig',
    tableName: 'table_configs',
    timestamps: true,
    underscored: true,
    indexes: [
      {
        fields: ['tenant_id'],
      },
      {
        fields: ['code'],
        unique: true,
      },
      {
        fields: ['status'],
      },
    ],
  }
);

export default TableConfig;
